﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using BF.Membership.BLL;
using BF.IBLL.BaseSystem;
using Base.Core.UnityFactory;
using System.Web.UI.HtmlControls;

namespace BF.Web.pages.BaseSystem.RolePermissionManagement
{
    public partial class RolePermissionList : BasePage
    {
        #region 实例
        AspnetRolesBLL rolesBLL = new AspnetRolesBLL();
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindList();
            }

        }

        private void BindList()
        {
            string[] roles =
                Roles.IsUserInRole(User.Identity.Name, "超级管理员")
                ? Roles.GetAllRoles()
                : Roles.GetRolesForUser();
            Repeater1.DataSource = rolesBLL.GetList(roles);
            Repeater1.DataBind();
        }


        protected void lbtnQuery_Click(object sender, EventArgs e)
        {
            BindList();
        }

        protected void lbtnDelete_Click(object sender, EventArgs e)
        {
            Isys_PermissionBLL iBLL = IOCFactory.GetIOCResolve<Isys_PermissionBLL>();
            bool result = false;
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                HtmlInputCheckBox cb = (HtmlInputCheckBox)Repeater1.Items[i].FindControl("chkKey");
                HtmlInputHidden hd = (HtmlInputHidden)Repeater1.Items[i].FindControl("RoleName");
                if (cb != null && cb.Checked)
                {
                    if (hd.Value == "超级管理员")
                    {
                        Messages("超级管理员角色不能被删除!", this.UpdatePanel1);
                    }
                    else
                    {
                        result = iBLL.DeleteRole(hd.Value);
                    }
                }
            }
            Messages(result ? "删除成功!" : "此角色正在被用户使用，不能被删除!", this.UpdatePanel1);
            BindList();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Isys_PermissionBLL iBLL = IOCFactory.GetIOCResolve<Isys_PermissionBLL>();
            string tmp = hidSelectNodes.Value;

            List<string> selectNodeIDs = tmp.Split(',').ToList<string>();
            for (int i = 0; i < selectNodeIDs.Count; i++)
            {
                selectNodeIDs[i] = selectNodeIDs[i].Trim();
            }

            if (iBLL.SetRolePermission(selectNodeIDs, hidRoleName.Value.Trim(), GetSessionCurrentUserInfo.sLoginName))
                Messages("保存成功!");
            else
                Messages("保存失败!");
        }
    }
}